import {Component, OnInit} from '@angular/core';
import {ExtendHttpService} from "../../services/extend-http.service";
import {TipService} from "../../services/tip.service";
import {Router} from "@angular/router";
import {Subscription} from "rxjs";
import {SocketService} from "../../services/socket.service";

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  tipType = 'error';

  // 统计数据
  statistics = {
    "balance": '',//账户余额，及总资产
    "totalTurnover": '',//总营业额
    "yesterdayIncome": '',//昨日收益
    "totalIncome": ''//累计收益
  };

  // 实时消费数据
  turnoverRecord = {
    "create_time": '',//交易时间
    "money": '',//交易金额
    "expectedEarnings": '',//预计收益
    "shop_name": ''//店铺名称
  }

  // 实时消费数据没有状态
  turnoverRecordState = false;

  // 接受到socket消息后改变状态，文字信息加滚动效果
  gunDong = false;

  // 获取今日数据
  dayData= {
    "turnoverConsumption" : '',//今日营业额
    "profit":''//预计收益
  }

  // socket
  unMsMessage: Subscription;

  // 折线图
  lineData = {
    time: [],
    list: []
  }

  myChart = null;

  constructor(private extendHttp: ExtendHttpService,
              private tipService: TipService,
              private router: Router,
              private socketService: SocketService
  ) {
  }

  ngOnInit() {

    this.myChart = echarts.init(document.getElementById('echarts'))

    // 监听socket
    this.unMsMessage = this.socketService.wsMessage.subscribe(data=>{
      if (data.code == '1501') {

        setTimeout(()=> {
          this.getSocketRealTimeData();
          this.getDayData();
          this.getLineData();
        }, 2000);

      }
    });

    this.getData();

    this.getRealTimeData();

    this.getDayData();

    this.getLineData();

  }

  // 获取统计数据
  getData() {
    this.extendHttp.get('/agentApp/info/getMyTurnoverStatistics', {}).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        this.statistics = res['statistics'];
        this.gunDong = true;
        setTimeout(()=>{
          this.gunDong = false;
        }, 1500);
      } else if (res['code'] == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1500);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  // 获取实时消费数据
  getRealTimeData() {
    this.extendHttp.get('/agentApp/info/getRollingContent', {}).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        if (res && res.turnoverRecord) {
          this.turnoverRecord = res['turnoverRecord'];
        } else {
          this.turnoverRecordState = true;
        }
      } else if (res['code'] == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1500);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  // 接受到socket消息后获取实时消费数据
  getSocketRealTimeData() {
    this.extendHttp.get('/agentApp/info/getRollingContent', {}).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        this.turnoverRecord = res['turnoverRecord'];
        this.gunDong = true;
        setTimeout(()=>{
          this.gunDong = false;
        }, 3000)
      } else if (res['code'] == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1500);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  // 获取今日数据
  getDayData() {
    this.extendHttp.get('/agentApp/info/getTodayStatistics', {}).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        this.dayData.turnoverConsumption = res.turnoverConsumption;
        this.dayData.profit = res.profit;
      } else if (res['code'] == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1500);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  // 最近收益折线图数据
  getLineData() {
    this.extendHttp.get('/agentApp/info/getBrokenLineStore', {}).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {

        if (res.list.length) {
          this.lineData.list = [];
          this.lineData.time = [];
          res.list.forEach(k=>{
            this.lineData.list.push(k.expectedEarnings);
            this.lineData.time.push(k.time.substr(14));
          })


          let option = {
            xAxis: {
              type: 'category',
              data: this.lineData.time
            },
            yAxis: {
              type: 'value'
            },
            series: [{
              data: this.lineData.list,
              type: 'line'
            }],
            grid: {
              top:'5%',
              bottom:'10%',
              right: '5%'
            }
          };
          this.myChart.setOption(option);
        }

      } else if (res['code'] == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1500);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

}
